package com.witmore.neutron.ai.web.apiv2.controller;

import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RolePermissionBindParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RoleQueryParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.RoleResult;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.RoleService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * V2 角色管理相关接口
 * Author: 豆子高
 * Date: 2025/9/17
 */
@Slf4j
@RestController
@RequestMapping("/v2/role")
public class RoleControllerV2 {

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询角色列表
     */
    @RequiresPermission("role:list")
    @PostMapping("/list")
    public ResponsePageResult<RoleResult> getRoleList(@RequestBody RoleQueryParam queryParam) {
        try {
            return roleService.getRolePage(queryParam);
        } catch (Exception e) {
            log.error("查询角色列表失败", e);
            return ResponsePageResult.fail(500, "查询角色列表失败: " + e.getMessage());
        }
    }

    /**
     * 角色与权限绑定
     */
    @RequiresPermission("role:bindPermission")
    @PostMapping("/bindPermissions")
    public ResponseResult<Boolean> bindRolePermissions(@Valid @RequestBody RolePermissionBindParam bindParam) {
        try {
            String creator = "system"; // 默认创建者，实际项目中应从会话中获取
            UserSession userSession = GlobalAccountSession.getUserInfo();
            if (userSession != null && userSession.getUserName() != null) {
                creator = userSession.getUserName();
            }
            
            boolean result = roleService.bindRolePermissions(bindParam, creator);
            if (result) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.fail(500, "角色权限绑定失败");
            }
        } catch (Exception e) {
            log.error("角色权限绑定失败", e);
            return ResponseResult.fail(500, "角色权限绑定失败: " + e.getMessage());
        }
    }
}